package com.company.project.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * IntelliJ IDEA.
 * User: lwb
 * Date: 2018/1/19
 * Time: 15:53
 * function:
 */
public class SignUtil
{
    /**
     * 一个简单的签名认证，规则：
     * 1. 将请求参数按ascii码排序
     * 2. 拼接为a=value&b=value...这样的字符串
     * 3. 混合密钥（secret）进行md5获得签名，与请求的签名进行比较
     * signName 签名key signName=19e907700db7ad91318424a97c54ed57
     * secret 密钥key DigestUtils.md5Hex(linkString + secret);//混合密钥md5
     */
    private boolean signValidate(HttpServletRequest request , String signName , String  secret)
    {
        String requestSign = request.getParameter(signName);//获得请求签名，signName=19e907700db7ad91318424a97c54ed57
        if (StringUtils.isEmpty(requestSign))
        {
            return false;
        }
        List<String> keys = new ArrayList<String>(request.getParameterMap().keySet());
        keys.remove(signName);//排除sign参数
        Collections.sort(keys);//排序

        StringBuilder sb = new StringBuilder();
        for (String key : keys)
        {
            sb.append(key).append("=").append(request.getParameter(key)).append("&");//拼接字符串
        }
        String linkString = sb.toString();
        linkString = StringUtils.substring(linkString, 0, linkString.length() - 1);//去除最后一个'&'

        String sign = DigestUtils.md5Hex(linkString + secret);//混合密钥md5

        return StringUtils.equals(sign, requestSign);//比较
    }

}
